package com.mida.dms.knw.service.impl;

import com.mida.dms.knw.Result.BaseResult;
import com.mida.dms.knw.config.enumData.FrontendReportRule;
import com.mida.dms.knw.entity.KnwNoumenon;
import com.mida.dms.knw.entity.KnwNoumenonRule;
import com.mida.dms.knw.entity.KnwNoumenonUserSpace;
import com.mida.dms.knw.entity.vo.*;
import com.mida.dms.knw.mapper.*;
import com.mida.dms.knw.service.KnwNoumenonRuleService;
import com.mida.dms.knw.service.KnwNoumenonService;
import com.mida.dms.knw.service.SoidService;
import com.mida.dms.knw.util.CharTransFormUtil;
import com.mida.dms.knw.vo.KnwNoumenonPageVo;
import com.mida.dms.knw.vo.KnwNoumenonUserSpaceBatchVo;
import com.mida.dms.knw.vo.Page;
import com.mida.dms.knw.vo.PageResultVo;
import com.mida.tool.common.result.ActionResult;
import com.mida.tool.common.result.ListResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.StopWatch;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.math.BigDecimal;
import java.util.*;

/**
 * <h1>本体服务实现</h1>
 * <p>
 *
 * @author jian.li on 2021/2/25 15:28
 */
@Slf4j
@Service
public class KnwNoumenonServiceImpl extends BaseResult implements KnwNoumenonService {

    /**
     * TagLabel
     */
    private static final String TAG_LABEL = "TagLabel";

    private static KnwNoumenon knwNoumenon = new KnwNoumenon();

    private static KnwNoumenonRule knwNoumenonRule = new KnwNoumenonRule();

    @Autowired
    private SoidService soidService;

    @Autowired
    private KnwNoumenonMapper knwNoumenonMapper;

    @Autowired
    private KnwNoumenonRelationMapper knwNoumenonRelationMapper;

    @Autowired
    private KnwNoumenonRuleService knwNoumenonRuleService;

    @Autowired
    private KnwNoumenonRuleMapper knwNoumenonRuleMapper;


    @Autowired
    private DtHistoryVersionMapper dtHistoryVersionMapper;

    @Autowired
    private KnwNoumenonUserSpaceMapper knwNoumenonUserSpaceMapper;

    @Autowired
    private KnwSlotMapper knwSlotMapper;


    @Autowired
    private KnwIndividualSoltMapper knwIndividualSoltMapper;


    @Override
    @Transactional(value = "dtdTxManager", rollbackFor = Exception.class)
    public ActionResult add(com.mida.dms.knw.vo.KnwNoumenonVo knwNoumenonVo) {
        if (knwNoumenonVo.getNoumenonSoid() != null) {
            log.info(knwNoumenon.toString() + "不是一个新增,转到更新");
            return update(knwNoumenonVo);
        }
        StopWatch stopWatch = StopWatch.createStarted();
        ActionResult actionResult = new ActionResult();
        try {
            knwNoumenon = convertToKnwNoumenon(knwNoumenonVo);
            log.info("开始新增一个本体: " + knwNoumenon.toString());

            if (knwNoumenon.getStatus() != 147L) {
                buildBadRequestActionWarn(actionResult, "新增本体不能为非草稿状态");
                return actionResult;
            }

            if (knwNoumenon.getVerson() != null) {
                buildBadRequestActionWarn(actionResult, "新增本体不能有版本号");
                return actionResult;
            }

            if (knwNoumenon.getNoumenonType() == null || knwNoumenon.getNoumenonType() == 0L) {
                buildBadRequestActionWarn(actionResult, "本体分类代码不能为空");
                return actionResult;
            }

            if (knwNoumenon.getNoumenonSubType() == null || knwNoumenon.getNoumenonType() == 0L) {
                buildBadRequestActionWarn(actionResult, "本体二级分类代码不能为空");
                return actionResult;
            }

            if (StringUtils.isEmpty(knwNoumenon.getNoumenonShowName())) {
                buildBadRequestActionWarn(actionResult, "本体显示名称不能为空");
                return actionResult;
            }

            if (StringUtils.isEmpty(knwNoumenon.getNoumenonShowName())) {
                buildBadRequestActionWarn(actionResult, "本体名称不能为空");
                return actionResult;
            }

            int count = knwNoumenonMapper.countName(knwNoumenon);
            if (count > 0) {
                buildBadRequestActionWarn(actionResult, "名称已存在");
                return actionResult;
            }

            knwNoumenon.setIsDelete(0L);
            knwNoumenon.setStatus(147L);
            knwNoumenon.setCreateDate(new Date());
            knwNoumenon.setUpdateDate(new Date());
            knwNoumenon.setUpdateUser(null);
            knwNoumenon.setPyCode(CharTransFormUtil.toPinyinSimple(knwNoumenon.getNoumenonShowName()));
            knwNoumenon.setWbCode(CharTransFormUtil.toWubi(knwNoumenon.getNoumenonShowName()));
//            Long knwNoumenonSoid = oIDGanerator.getSOID();
            Long knwNoumenonSoid = soidService.getSoid();
            knwNoumenon.setNoumenonSoid(knwNoumenonSoid);

            // 添加本体标签
            knwNoumenon.setLable(FrontendReportRule.TAG_EX.getCodeName());
            knwNoumenonMapper.insert(knwNoumenon);

            //国标
            soidService.insertOid(knwNoumenonSoid, 1);
//            String oid = oIDGanerator.getOID(1);
//            DtOid dtOid = new DtOid();
//            dtOid.setOid(oid);
//            dtOid.setSoid(knwNoumenonSoid);
//            dtOidMapper.insert(dtOid);

            //本体规则
            if (knwNoumenonVo.getRuleDetailCodingSystemSoid() != null) {
                knwNoumenonRule = convertToKnwNoumenonRule(knwNoumenonVo);
                knwNoumenonRule.setNoumenonSoid(knwNoumenonSoid);
                knwNoumenonRule.setIsDelete(0L);
                log.info("开始新增一个本体规则: " + knwNoumenonRule.toString());
                knwNoumenonRule.setCreateDate(new Date());
                knwNoumenonRule.setUpdateDate(new Date());
//                Long noumenonRuleSoid = oIDGanerator.getSOID();
                Long noumenonRuleSoid = soidService.getSoid();
                knwNoumenonRule.setNoumenonRuleSoid(noumenonRuleSoid);
                knwNoumenonRuleMapper.insert(knwNoumenonRule);

                //国标
                soidService.insertOid(knwNoumenonSoid, 1);
//                String ruleOid = oIDGanerator.getOID(1);
//                DtOid ruleDtOid = new DtOid();
//                ruleDtOid.setOid(ruleOid);
//                ruleDtOid.setSoid(knwNoumenonSoid);
//                dtOidMapper.insert(ruleDtOid);
            }

            //授权空间关系
            List<Long> useSpaceList = knwNoumenonVo.getUseSpaceList();
            if (useSpaceList != null) {
                if (useSpaceList.size() > 0) {
                    for (int i = 0; i < useSpaceList.size(); i++) {
                        KnwNoumenonUserSpace us = new KnwNoumenonUserSpace();
//                        Long usSoid = oIDGanerator.getSOID();
                        Long usSoid = soidService.getSoid();
                        us.setNoumenonSpaceSoid(usSoid);
                        us.setNoumenonSoid(knwNoumenonSoid);
                        us.setUseSpaceSoid(useSpaceList.get(i));
                        us.setStatus(149L);
                        us.setIsDelete(0L);
                        us.setCreateDate(new Date());
                        us.setUpdateDate(new Date());
                        us.setUpdateUser(null);
                        knwNoumenonUserSpaceMapper.insert(us);

                        //国标
                        soidService.insertOid(usSoid, 1);
//                        String usoid = oIDGanerator.getOID(1);
//                        DtOid usDtOid = new DtOid();
//                        usDtOid.setOid(usoid);
//                        usDtOid.setSoid(usSoid);
//                        dtOidMapper.insert(usDtOid);
                    }
                }
            }
            buildActionSuccess(actionResult);
        } catch (Exception e) {
            log.error("新增本体发送异常", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            buildActionWarn(actionResult, "新增本体失败");
        } finally {
            stopWatch.stop();
            log.info("本次新增耗时: " + stopWatch.getTime() + "ms");
        }
        return actionResult;
    }

    @Override
    @Transactional(value = "dtdTxManager", rollbackFor = Exception.class)
    public ActionResult delete(Long soid) {
        log.info("开始删除一个本体: " + soid);
        StopWatch stopWatch = StopWatch.createStarted();
        ActionResult actionResult = new ActionResult();
        try {
            KnwNoumenon knwNoumenon = knwNoumenonMapper.selectByPrimaryKey(soid);
            if (knwNoumenon.getStatus().longValue() == 145L) {
                buildBadRequestActionWarn(actionResult, "本体已启用,无法删除");
                return actionResult;
            }
            //删除前检查本体是否有实例
            int individualNo = knwNoumenonMapper.countIndividual(soid);
            if (individualNo > 0) {
                buildBadRequestActionWarn(actionResult, "本体存在实例,无法删除");
                return actionResult;
            }
            //删除本体
            knwNoumenonMapper.deleteByPrimaryKey(soid);
            KnwNoumenonRule knwNoumenonRule = knwNoumenonRuleMapper.findByKnwNoumenonSoid(soid);
            if (knwNoumenonRule != null) {
                //删除本体规则
                knwNoumenonRuleMapper.deleteByPrimaryKey(knwNoumenonRule.getNoumenonRuleSoid());
            }
            //删除本体slot
            knwNoumenonMapper.deleteSlot(soid);
            //删除本体历史记录
            dtHistoryVersionMapper.deleteKnwNoumenonHistory(soid);
            //删除授权关系表记录
            knwNoumenonUserSpaceMapper.deleteByNoumenonSoid(soid);
            buildActionSuccess(actionResult);
        } catch (Exception e) {
            log.error("删除本体发送异常", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            buildActionWarn(actionResult, "删除本体失败");
        } finally {
            stopWatch.stop();
            log.info("本次删除耗时: " + stopWatch.getTime() + "ms");
        }
        return actionResult;
    }

    @Override
    @Transactional(value = "dtdTxManager", rollbackFor = Exception.class)
    public ActionResult update(com.mida.dms.knw.vo.KnwNoumenonVo knwNoumenonVo) {
        knwNoumenon = convertToKnwNoumenon(knwNoumenonVo);
        log.info("开始更新一个本体" + knwNoumenon.toString());
        StopWatch stopWatch = StopWatch.createStarted();
        ActionResult actionResult = new ActionResult();
        try {
            KnwNoumenon kn = knwNoumenonMapper.selectByPrimaryKey(knwNoumenon.getNoumenonSoid());
            if (kn == null) {
                buildBadRequestActionWarn(actionResult, "本体不存在: " + knwNoumenon.getNoumenonSoid());
                return actionResult;
            }
            if (knwNoumenon.getNoumenonType() == null || knwNoumenon.getNoumenonType() == 0L) {
                buildBadRequestActionWarn(actionResult, "本体分类代码不能为空");
                return actionResult;
            }

            if (knwNoumenon.getNoumenonSubType() == null || knwNoumenon.getNoumenonType() == 0L) {
                buildBadRequestActionWarn(actionResult, "本体二级分类代码不能为空");
                return actionResult;
            }

            //因本体只有草稿状态才能更新,所以只要传入版本号不为空即报错
            if (knwNoumenon.getVerson() != null) {
                buildBadRequestActionWarn(actionResult, "版本更新只能通过发布接口");
                return actionResult;
            }

            if (StringUtils.isEmpty(knwNoumenon.getNoumenonShowName())) {
                buildBadRequestActionWarn(actionResult, "本体显示名称不能为空");
                return actionResult;
            }

            if (StringUtils.isEmpty(knwNoumenon.getNoumenonName())) {
                buildBadRequestActionWarn(actionResult, "本体名称不能为空");
                return actionResult;
            }

            //本体一级类型,二级类型,本体显示名称产生变化
            if (kn.getNoumenonType().compareTo(knwNoumenon.getNoumenonType()) != 0 ||
                    kn.getNoumenonSubType().compareTo(knwNoumenon.getNoumenonSubType()) != 0 ||
                    !StringUtils.equals(kn.getNoumenonShowName(), knwNoumenon.getNoumenonShowName())) {
                int count = knwNoumenonMapper.countName(knwNoumenon);
                if (count > 0) {
                    buildBadRequestActionWarn(actionResult, "名称已存在");
                    return actionResult;
                }
            }

            //(草稿 -> 启用),(草稿 -> 停用)
            if (kn.getStatus().longValue() == 147L && knwNoumenonVo.getStatus().longValue() != 147L) {
                buildBadRequestActionWarn(actionResult, "草稿状态本体无法通过编辑更新状态");
                return actionResult;
            }
            //(启用 -> 草稿)
            if (kn.getStatus().longValue() == 145L && knwNoumenonVo.getStatus().longValue() == 147L) {
                buildBadRequestActionWarn(actionResult, "启用状态本体无法更新为草稿状态");
                return actionResult;
            }
            //停用
            if (kn.getStatus().longValue() == 146L) {
                buildBadRequestActionWarn(actionResult, "本体已停用,无法更新");
                return actionResult;
            }
            //停用本体判断(启用 -> 停用)
            if (kn.getStatus().longValue() == 145L && knwNoumenonVo.getStatus().longValue() == 146L) {
                int count = knwNoumenonMapper.countIndividual(knwNoumenon.getNoumenonSoid());
                if (count > 0) {
                    buildBadRequestActionWarn(actionResult, "本体有实例仍为启用,无法停用该本体");
                    return actionResult;
                }
            }

            knwNoumenon.setIsDelete(0L);
            knwNoumenon.setPyCode(CharTransFormUtil.toPinyinSimple(knwNoumenon.getNoumenonShowName()));
            knwNoumenon.setWbCode(CharTransFormUtil.toWubi(knwNoumenon.getNoumenonShowName()));
            knwNoumenon.setUpdateDate(new Date());
            knwNoumenonMapper.updateByPrimaryKeySelective(knwNoumenon);

            //本体规则
            //根据本体soid查询出的本体规则
            KnwNoumenonRule knr = knwNoumenonRuleMapper.findByKnwNoumenonSoid(knwNoumenonVo.getNoumenonSoid());
            //本体有对应规则的情况
            if (knr != null) {
                knwNoumenonRule = convertToKnwNoumenonRule(knwNoumenonVo);
                knwNoumenonRule.setNoumenonRuleSoid(knr.getNoumenonRuleSoid());
                knwNoumenonRule.setIsDelete(0L);
                knwNoumenonRule.setUpdateDate(new Date());
                knwNoumenonRuleMapper.updateByPrimaryKeySelective(knwNoumenonRule);
                //本体无对应规则并且新增了规则
            } else if (knr == null && knwNoumenonVo.getRuleDetailCodingSystemSoid() != null) {
                knwNoumenonRule = convertToKnwNoumenonRule(knwNoumenonVo);
                knwNoumenonRule.setNoumenonSoid(knwNoumenonVo.getNoumenonSoid());
                knwNoumenonRule.setIsDelete(0L);
                log.info("开始新增一个本体规则: " + knwNoumenonRule.toString());
                knwNoumenonRule.setCreateDate(new Date());
                knwNoumenonRule.setUpdateDate(new Date());
//                knwNoumenonRule.setNoumenonRuleSoid(oIDGanerator.getSOID());
                knwNoumenonRule.setNoumenonRuleSoid(soidService.getSoid());
                knwNoumenonRuleMapper.insert(knwNoumenonRule);
            }

            //授权空间关系
            //vo的本体相关授权空间关系soid
            List<Long> useSpaceList = knwNoumenonVo.getUseSpaceList();
            //该本体相关的授权空间关系soid
            List<Long> selectedSpaceList = knwNoumenonUserSpaceMapper.getUseSpaceList(knwNoumenonVo.getNoumenonSoid());
            //原本体无授权空间关系,现有新增
            if (selectedSpaceList == null && useSpaceList != null) {
                if (useSpaceList.size() > 0) {
                    for (int i = 0; i < useSpaceList.size(); i++) {
                        KnwNoumenonUserSpace us = new KnwNoumenonUserSpace();
//                        Long usSoid = oIDGanerator.getSOID();
                        Long usSoid = soidService.getSoid();

                        us.setNoumenonSpaceSoid(usSoid);
                        us.setNoumenonSoid(knwNoumenonVo.getNoumenonSoid());
                        us.setUseSpaceSoid(useSpaceList.get(i));
                        us.setStatus(149L);
                        us.setIsDelete(0L);
                        us.setCreateDate(new Date());
                        us.setUpdateDate(new Date());
                        us.setUpdateUser(null);
                        knwNoumenonUserSpaceMapper.insert(us);

                        //国标
                        soidService.insertOid(usSoid, 1);
//                        String usoid = oIDGanerator.getOID(1);
//                        DtOid usDtOid = new DtOid();
//                        usDtOid.setOid(usoid);
//                        usDtOid.setSoid(usSoid);
//                        dtOidMapper.insert(usDtOid);
                    }
                }
            }

            //原本体有授权空间关系,现全部删除
            if (selectedSpaceList != null && useSpaceList == null) {
                for (int i = 0; i < selectedSpaceList.size(); i++) {
                    knwNoumenonUserSpaceMapper.deleteByNoumenonSoidAndUseSpaceSoid(knwNoumenonVo.getNoumenonSoid(), selectedSpaceList.get(i));
                }
            }

            //原本体有授权空间关系,vo本体也有授权空间关系
            if (selectedSpaceList != null && useSpaceList != null) {
                //该本体授权关系产生变化
                if (useSpaceList.size() != selectedSpaceList.size() || !useSpaceList.containsAll(selectedSpaceList)) {
                    for (int i = 0; i < selectedSpaceList.size(); i++) {
                        knwNoumenonUserSpaceMapper.deleteByNoumenonSoidAndUseSpaceSoid(knwNoumenonVo.getNoumenonSoid(), selectedSpaceList.get(i));
                    }

                    for (int i = 0; i < useSpaceList.size(); i++) {
                        KnwNoumenonUserSpace us = new KnwNoumenonUserSpace();
//                        Long usSoid = oIDGanerator.getSOID();
                        Long usSoid = soidService.getSoid();
                        us.setNoumenonSpaceSoid(usSoid);
                        us.setNoumenonSoid(knwNoumenonVo.getNoumenonSoid());
                        us.setUseSpaceSoid(useSpaceList.get(i));
                        us.setStatus(149L);
                        us.setIsDelete(0L);
                        us.setCreateDate(new Date());
                        us.setUpdateDate(new Date());
                        us.setUpdateUser(null);
                        knwNoumenonUserSpaceMapper.insert(us);

                        //国标
                        soidService.insertOid(usSoid, 1);
//                        String usoid = oIDGanerator.getOID(1);
//                        DtOid usDtOid = new DtOid();
//                        usDtOid.setOid(usoid);
//                        usDtOid.setSoid(usSoid);
//                        dtOidMapper.insert(usDtOid);
                    }
                }
            }
            buildActionSuccess(actionResult);
        } catch (Exception e) {
            log.error("更新本体发送异常", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            buildActionWarn(actionResult, "更新本体失败");
        } finally {
            stopWatch.stop();
            log.info("本次更新耗时: " + stopWatch.getTime() + "ms");
        }

        return actionResult;
    }

    @Override
    public ActionResult checkName(Long originalSoid, Long newNoumenonType, Long newNoumenonSubType, String newNoumenonShowName) {
        log.info("开始检查是否重名");
        StopWatch stopWatch = StopWatch.createStarted();
        ActionResult actionResult = new ActionResult();
        try {
            if (newNoumenonType == null) {
                buildBadRequestActionWarn(actionResult, "传入本体类型不能为空");
                return actionResult;
            }
            KnwNoumenon k = new KnwNoumenon();
            k.setNoumenonType(newNoumenonType);
            k.setNoumenonSubType(newNoumenonSubType);
            k.setNoumenonShowName(newNoumenonShowName);
            if (originalSoid == null) {
                log.info("check:新增操作");
                int count = knwNoumenonMapper.countName(k);
                if (count > 0) {
                    buildBadRequestActionWarn(actionResult, "本体名已存在");
                    return actionResult;
                }
            } else if (originalSoid != null) {
                log.info("check:更新操作");
                KnwNoumenon knwNoumenon = knwNoumenonMapper.selectByPrimaryKey(originalSoid);
                if (knwNoumenon == null) {
                    buildBadRequestActionWarn(actionResult, "原本体不存在");
                    return actionResult;
                }

                //本体一级类型,二级类型,本体显示名称产生变化
                if (newNoumenonType.compareTo(knwNoumenon.getNoumenonType()) == 0 ||
                        newNoumenonSubType.compareTo(knwNoumenon.getNoumenonSubType()) != 0 ||
                        !StringUtils.equals(newNoumenonShowName, knwNoumenon.getNoumenonShowName())) {
                    int count = knwNoumenonMapper.countName(k);
                    if (count > 0) {
                        buildBadRequestActionWarn(actionResult, "名称已存在");
                        return actionResult;
                    }
                }
            }
            buildActionSuccess(actionResult);
        } catch (Exception e) {
            log.error("检查本体发送异常", e);
            buildActionWarn(actionResult, "检查本体发送异常");
        } finally {
            stopWatch.stop();
            log.info("本次检查耗时: " + stopWatch.getTime() + "ms");
        }
        return actionResult;
    }

    @Override
    public ListResult<KnwNoumenonVo> get(Long soid) {
        log.info("开始查询一个本体: " + soid);
        StopWatch stopWatch = StopWatch.createStarted();
        ListResult<KnwNoumenonVo> listResult = new ListResult<KnwNoumenonVo>();
        try {
            KnwNoumenonVo single = knwNoumenonMapper.findSingle(soid);
            List<KnwNoumenonUserSpaceVo> useSpaceCodeAndName = knwNoumenonUserSpaceMapper.getUseSpaceCodeAndName(soid);
            if (useSpaceCodeAndName != null && useSpaceCodeAndName.size() > 0) {
                single.setUserSpaceList(useSpaceCodeAndName);
                //拼接授权空间名称
                StringBuffer stringBuffer = new StringBuffer();
                StringBuffer seperation = new StringBuffer("|");
                for (int i = 0; i < useSpaceCodeAndName.size(); i++) {
                    stringBuffer.append(useSpaceCodeAndName.get(i).getValue()).append(seperation);
                }
                if (stringBuffer.length() > 1) {
                    single.setUserSpaceListPage(stringBuffer.substring(0, stringBuffer.length() - 1));
                } else {
                    single.setUserSpaceListPage(stringBuffer.toString());
                }
            }
            buildListSuccess(listResult, single);
        } catch (Exception e) {
            log.error("查询本体发送异常: ", e);
            buildListWarn(listResult, "查询本体失败");
        } finally {
            stopWatch.stop();
            log.info("本次查询耗时: " + stopWatch.getTime() + "ms");
        }
        return listResult;
    }

    @Override
    public ListResult<PageResultVo<KnwNoumenonVo>> findPage(KnwNoumenonPageVo vo) {
        log.info("开始本体分页查询,查询条件: " + vo.toString());
        ListResult result = new ListResult();
        PageResultVo pageResultVo = new PageResultVo();
        Page page = new Page(vo.getCurrentPage(), vo.getPageSize());
        pageResultVo.setPage(page);
        StopWatch stopWatch = StopWatch.createStarted();

        List<KnwNoumenonVo> list = null;
        try {
            KnwNoumenonPage npage = new KnwNoumenonPage(vo.getCurrentPage(), vo.getPageSize(), vo.getSearchData(), vo.getNoumenonType(), vo.getNoumenonSubType(), null);
            //根据本体ID,本体名称,拼音码,五笔码模糊查询
            int count = knwNoumenonMapper.findPageCount(npage);
            if (count > 0) {
                page.setTotalCount(count);
                list = knwNoumenonMapper.findPage(npage);
                for (KnwNoumenonVo knwNoumenonVo : list) {
                    if (knwNoumenonVo.getIndividualNumber() == null) {
                        knwNoumenonVo.setIndividualNumber(0);
                    }

                    if (knwNoumenonVo.getSlotNumber() == null) {
                        knwNoumenonVo.setSlotNumber(0);
                    }
                    List<KnwNoumenonUserSpaceVo> useSpaceCodeAndName = knwNoumenonUserSpaceMapper.getUseSpaceCodeAndName(knwNoumenonVo.getNoumenonSoid());
                    if (useSpaceCodeAndName != null && useSpaceCodeAndName.size() > 0) {
                        knwNoumenonVo.setUserSpaceList(useSpaceCodeAndName);
                        StringBuffer stringBuffer = new StringBuffer();
                        StringBuffer seperation = new StringBuffer("|");
                        for (int i = 0; i < useSpaceCodeAndName.size(); i++) {
                            stringBuffer.append(useSpaceCodeAndName.get(i).getValue()).append(seperation);
                        }
                        if (stringBuffer.length() > 1) {
                            knwNoumenonVo.setUserSpaceListPage(stringBuffer.substring(0, stringBuffer.length() - 1));
                        } else {
                            knwNoumenonVo.setUserSpaceListPage(stringBuffer.toString());
                        }
                    }
                }
            } else {
                page.setTotalCount(count);
                list = new ArrayList<KnwNoumenonVo>(0);
            }
            pageResultVo.setList(list);
            buildListSuccess(result, pageResultVo);
        } catch (Exception e) {
            list = new ArrayList<KnwNoumenonVo>(0);
            pageResultVo.setList(list);
            log.error("分页查询本体发送异常", e);
            buildListWarn(result, "分页查询本体失败");
        } finally {
            stopWatch.stop();
            log.info("本次分页查询耗时: " + stopWatch.getTime() + "ms");
        }
        return result;
    }

    KnwNoumenon convertToKnwNoumenon(com.mida.dms.knw.vo.KnwNoumenonVo vo) {
        knwNoumenon.setNoumenonSoid(vo.getNoumenonSoid());
        knwNoumenon.setConceptualSoid(vo.getConceptualSoid());
        knwNoumenon.setDefineSpaceSoid(vo.getDefineSpaceSoid());
        knwNoumenon.setMdmSoid(vo.getMdmSoid());
        knwNoumenon.setNoumenonName(vo.getNoumenonName());
        knwNoumenon.setNoumenonShowName(vo.getNoumenonShowName());
        knwNoumenon.setPyCode(vo.getPyCode());
        knwNoumenon.setWbCode(vo.getWbCode());
        knwNoumenon.setNoumenonDesc(vo.getNoumenonDesc());
        knwNoumenon.setNoumenonType(vo.getNoumenonType());
        knwNoumenon.setVerson(vo.getVersion());
        knwNoumenon.setCreateDate(vo.getCreateDate());
        knwNoumenon.setUpdateDate(vo.getUpdateDate());
        knwNoumenon.setUpdateUser(vo.getUpdateUser());
        knwNoumenon.setStatus(vo.getStatus());
        knwNoumenon.setIsDelete(vo.getIsDelete());
        knwNoumenon.setNoumenonSubType(vo.getNoumenonSubType());
        knwNoumenon.setNoumenonThirdType(vo.getNoumenonThirdType());
        knwNoumenon.setLable(vo.getLable());
        return knwNoumenon;
    }

    KnwNoumenonRule convertToKnwNoumenonRule(com.mida.dms.knw.vo.KnwNoumenonVo vo) {
        knwNoumenonRule.setNoumenonRuleSoid(vo.getNoumenonRuleSoid());
        knwNoumenonRule.setNoumenonSoid(vo.getNoumenonSoid());
        knwNoumenonRule.setNoumenonRuleName(vo.getNoumenonRuleName());
        knwNoumenonRule.setWbCode(vo.getRuleWbCode());
        knwNoumenonRule.setPyCode(vo.getRulePyCode());
        knwNoumenonRule.setNoumenonRuleDesc(vo.getNoumenonRuleDesc());
        knwNoumenonRule.setCreateDate(vo.getRuleCreateDate());
        knwNoumenonRule.setUpdateDate(vo.getRuleUpdateDate());
        knwNoumenonRule.setUpdateUser(vo.getUpdateUser());
        knwNoumenonRule.setStatus(vo.getRuleStatus());
        knwNoumenonRule.setIsDelete(vo.getRuleIsDelete());
        knwNoumenonRule.setDerailCodingSystemSoid(vo.getRuleDetailCodingSystemSoid());
        return knwNoumenonRule;
    }

    @Override
    public ListResult<List<KnwNoumenonVo>> findAll(String search) {
        log.info("开始查询所有概念域,查询条件:", search);
        StopWatch st = StopWatch.createStarted();
        ListResult result = new ListResult();
        List<KnwNoumenonVo> list = null;
        try {
            list = knwNoumenonMapper.findAll(search);
            buildListSuccess(result, list);
        } catch (Exception e) {
            list = new ArrayList<KnwNoumenonVo>(0);
            log.error("查询所有概念域发送异常", e);
            buildListWarn(result, "查询所有概念域失败");
        } finally {
            st.stop();
            log.info("本次查询所有概念域耗时:" + st.getTime() + "ms");
        }
        return result;
    }

    /**
     * 本体类型树状结构查询
     *
     * @return
     */
    @Override
    public ListResult<List<KnwNoumenonTreeVo>> getTree() {
        log.info("开始本体类型树状结构查询");
        ListResult result = new ListResult();
        List<KnwNoumenonTreeVo> tree = null;
        try {
            tree = knwNoumenonMapper.getTree();
            buildListSuccess(result, tree);
        } catch (Exception e) {
            log.error("本体类型树状结构查询异常", e);
            buildListWarn(result, "本体类型树状结构查询异常");
        }
        return result;
    }

    public ListResult<List<KnwNoumenonRelationVo>> getLocalAnatomyRootTree(Long noumenonSoid) {
        log.info("开始本体树(局部解剖学)根树查询");
        ListResult result = new ListResult();
        List<KnwNoumenonRelationVo> allRelation = knwNoumenonRelationMapper.findAllRelation();
        buildListSuccess(result, allRelation);
        return result;
    }

    @Override
    public ListResult<List<KnwNoumenonRelationVo>> getSubTree(Long noumenonSoid) {
        log.info("开始本体树(局部解剖学)子树查询");
        ListResult result = new ListResult();
        List<KnwNoumenonRelationVo> knwNoumenonRelations = knwNoumenonRelationMapper.selectByTargetSoid(noumenonSoid);
        buildListSuccess(result, knwNoumenonRelations);
        return result;
    }

    @Override
    public ActionResult bulkInsertknwNoumenonUserSpace(List<KnwNoumenonUserSpace> knwNoumenonUserSpaces) {
        ActionResult actionResult = new ActionResult();

        List<Long> soids = soidService.getSoids(knwNoumenonUserSpaces.size());
        for (int i = 0; i < knwNoumenonUserSpaces.size(); i++) {
            KnwNoumenonUserSpace knwNoumenonUserSpace = knwNoumenonUserSpaces.get(i);
            knwNoumenonUserSpace.setNoumenonSpaceSoid(soids.get(i));
        }
        knwNoumenonUserSpaceMapper.bulkInsertknwNoumenonUserSpace(knwNoumenonUserSpaces);
        buildActionSuccess(actionResult);
        return actionResult;
    }

    @Override
    public ActionResult batchCancelknwNoumenonUserSpace(List<KnwNoumenonUserSpace> knwNoumenonUserSpaces) {
        ActionResult actionResult = new ActionResult();

        knwNoumenonUserSpaceMapper.batchCancelknwNoumenonUserSpace(knwNoumenonUserSpaces);
        buildActionSuccess(actionResult);
        return actionResult;
    }

    @Override
    public ListResult<PageResultVo<KnwNoumenonVo>> selectKnwNoumenonVos(KnwNoumenonPageVo vo) throws Exception {
        log.info("开始本体分页查询,查询条件: " + vo.toString());
        ListResult result = new ListResult();
        PageResultVo pageResultVo = new PageResultVo();
        Page page = new Page(vo.getCurrentPage(), vo.getPageSize());
        pageResultVo.setPage(page);
        List<KnwNoumenonVo> list = null;

        KnwNoumenonPage npage = new KnwNoumenonPage(vo.getCurrentPage(), vo.getPageSize(), vo.getSearchData(), vo.getNoumenonType(), vo.getNoumenonSubType(), null,vo.getUseSpaceSoids());
        //根据本体ID,本体名称,拼音码,五笔码模糊查询
        int count = knwNoumenonMapper.findPageCounts(npage);
        if (count > 0) {
            page.setTotalCount(count);
            list = knwNoumenonMapper.selectKnwNoumenonVos(npage);
        } else {
            page.setTotalCount(count);
            list = new ArrayList<KnwNoumenonVo>(0);
        }
        pageResultVo.setList(list);
        buildListSuccess(result, pageResultVo);

        return result;
    }

    @Override
    public ListResult<PageResultVo<KnwNoumenonVo>> selectCancelKnwNoumenonVos(KnwNoumenonPageVo vo) {
        log.info("开始本体分页查询,查询条件: " + vo.toString());
        ListResult result = new ListResult();
        PageResultVo pageResultVo = new PageResultVo();
        Page page = new Page(vo.getCurrentPage(), vo.getPageSize());
        pageResultVo.setPage(page);
        List<KnwNoumenonVo> list = null;

        KnwNoumenonPage npage = new KnwNoumenonPage(vo.getCurrentPage(), vo.getPageSize(), vo.getSearchData(), vo.getNoumenonType(), vo.getNoumenonSubType(), null,vo.getUseSpaceSoids());
        //根据本体ID,本体名称,拼音码,五笔码模糊查询
        int count = knwNoumenonMapper.findCansolePageCounts(npage);
        if (count > 0) {
            page.setTotalCount(count);
            list = knwNoumenonMapper.selectCansoleKnwNoumenonVos(npage);
            for (KnwNoumenonVo knwNoumenonVo : list) {
                if (knwNoumenonVo.getIndividualNumber() == null) {
                    knwNoumenonVo.setIndividualNumber(0);
                }

                if (knwNoumenonVo.getSlotNumber() == null) {
                    knwNoumenonVo.setSlotNumber(0);
                }
                List<KnwNoumenonUserSpaceVo> useSpaceCodeAndName = knwNoumenonUserSpaceMapper.getUseSpaceCodeAndName(knwNoumenonVo.getNoumenonSoid());
                if (useSpaceCodeAndName != null && useSpaceCodeAndName.size() > 0) {
                    knwNoumenonVo.setUserSpaceList(useSpaceCodeAndName);
                    StringBuffer stringBuffer = new StringBuffer();
                    StringBuffer seperation = new StringBuffer("|");
                    for (int i = 0; i < useSpaceCodeAndName.size(); i++) {
                        stringBuffer.append(useSpaceCodeAndName.get(i).getValue()).append(seperation);
                    }
                    if (stringBuffer.length() > 1) {
                        knwNoumenonVo.setUserSpaceListPage(stringBuffer.substring(0, stringBuffer.length() - 1));
                    } else {
                        knwNoumenonVo.setUserSpaceListPage(stringBuffer.toString());
                    }
                }
            }
        } else {
            page.setTotalCount(count);
            list = new ArrayList<KnwNoumenonVo>(0);
        }
        pageResultVo.setList(list);
        buildListSuccess(result, pageResultVo);

        return result;
    }

    /**
     * 根据本体soid
     *
     * @param vo
     * @return
     * @throws Exception
     */
    @Override
    public ListResult<List<KnwNoumenonVo>> selectKnwNoumenonVoList(KnwNoumenonPageVo vo) throws Exception {
        ListResult listResult = new ListResult();
        if (vo.getUseSpaceSoids() == null || vo.getUseSpaceSoids().size() == 0) {
            return listResult;
        }

        Map<String, Object> map = new HashMap<>();
        map.put("useSpaceSoids", vo.getUseSpaceSoids());
        List<KnwNoumenonVo> listKnwNoumenonVo = knwNoumenonMapper.selectKnwNoumenonVoList(map);
        buildListSuccess(listResult, listKnwNoumenonVo);
        return listResult;
    }
}
